package com.ybkj.o2o.zhuanche.controller;

import com.google.common.base.Preconditions;
import com.alibaba.fastjson.JSONObject;
import com.ybkj.o2o.zhuanche.common.CompanyOrderVo;
import com.ybkj.o2o.zhuanche.common.DataGrid;
import com.ybkj.o2o.zhuanche.common.DriverOrderDetailVo;
import com.ybkj.o2o.zhuanche.common.DriverOrderVo;
import com.ybkj.o2o.zhuanche.common.InitChart;
import com.ybkj.o2o.zhuanche.common.MemberOrderVo;
import com.ybkj.o2o.zhuanche.common.OrderFromSourceVo;
import com.ybkj.o2o.zhuanche.common.PageVo;
import com.ybkj.o2o.zhuanche.common.api.DaijiaApi;
import com.ybkj.o2o.zhuanche.common.query.OrderQuery;
import com.ybkj.o2o.zhuanche.common.transport.Error;
import com.ybkj.o2o.zhuanche.common.transport.Result;
import com.ybkj.o2o.zhuanche.controller.v4.ErrorConstantV4;
import com.ybkj.o2o.zhuanche.controller.v4.ResultTransport;
import com.ybkj.o2o.zhuanche.entity.CarType;
import com.ybkj.o2o.zhuanche.entity.CarTypeRel;
import com.ybkj.o2o.zhuanche.entity.ChartDay;
import com.ybkj.o2o.zhuanche.entity.ChartMonth;
import com.ybkj.o2o.zhuanche.entity.ChartYear;
import com.ybkj.o2o.zhuanche.entity.Order;
import com.ybkj.o2o.zhuanche.entity.OrderMemo;
import com.ybkj.o2o.zhuanche.entity.OrderOrbit;
import com.ybkj.o2o.zhuanche.entity.OrderTemp;
import com.ybkj.o2o.zhuanche.manager.CarTypeManager;
import com.ybkj.o2o.zhuanche.manager.OrderManager;
import com.ybkj.o2o.zhuanche.manager.OrderMemoManager;
import com.ybkj.o2o.zhuanche.manager.OrderOrbitManager;
import com.ybkj.o2o.zhuanche.manager.OrderTempManager;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("api/orders")
public class OrderRes {
  
  @Autowired
  private OrderManager orderManager;
  
  @Autowired
  private OrderTempManager orderTempManager;

  @Autowired
  private OrderMemoManager orderMemoManager;

  @Autowired
  private OrderOrbitManager orderOrbitManager;

  @Autowired
  private CarTypeManager carTypeManager;

  @Autowired
  private InitChart initChart;
  
  @Autowired
  private DaijiaApi daijiaApi;

  @RequestMapping("migration")
  public  @ResponseBody  String migration(
      @RequestParam(required = false,value="appKey")String appKey) {
    initChart.migration(StringUtils.isNotBlank(appKey)?appKey:null);
    return "migration"+(StringUtils.isNotBlank(appKey)?"    appKey:"+appKey:"");
  }

  /**
   * 创建专车订单.
   * @param passengerId 客户Id
   * @param passengerName 客户姓名
   * @param passengerPhone 客户电话
   * @param companyId 公司Id
   * @param companyName 公司名称
   * @param carTypeId 车辆类型Id
   * @param channelName 订单来源
   * @param startAddress 出发地址
   * @param startAddressDetail 预约地详细地址
   * @param startLat 预约地经度
   * @param startLng 预约地纬度
   * @param endAddress 目的地地址
   * @param endAddressDetail 目的地详细地址
   * @param endLat 目的地经度
   * @param endLng 目的地纬度
   * @param serverTime 服务时间
   * @param budgetPay 预估总价
   * @param prestartPrice 预估开始价格
   * @param premileagePrice 预估里程价格
   * @param prerunTimePrice 预估服务时间价格
   * @param pretravelTime 预估时间
   * @param premileage 预估里程
   * @param prePay 是否预付费
   * @param employId 服务人员Id
   * @param employName 服务人员名称
   * @param employPhone 服务人员电话
   * @param employCompanyId 司机所在公司ID
   * @param employNo 服务人员工号
   * @param employPhoto 服务人员头像
   * @param employScore 服务人员综合评分
   * @param shouldPay 应该支付金额(减去优惠券以后的金额)
   */
  
  @RequestMapping(value = "create", method = RequestMethod.POST)
  public ResponseEntity<Object> create(
      @RequestParam("passengerId") Long passengerId,
      @RequestParam("passengerName") String passengerName,
      @RequestParam("passengerPhone") String passengerPhone,
      @RequestParam("showPhone") String showPhone, 
      @RequestParam("companyId") Long companyId,
      @RequestParam("companyName") String companyName, 
      @RequestParam("carTypeId") Long carTypeId,
      @RequestParam("channelName") String channelName,
      @RequestParam("serverTime") Long serverTime,
      @RequestParam("startLat") Double startLat,
      @RequestParam("startLng") Double startLng,
      @RequestParam("startAddress") String startAddress,
      @RequestParam(required = false,value = "startAddressDetail") String startAddressDetail,
      @RequestParam(required = false, value = "endAddress") String endAddress,
      @RequestParam(required = false, value = "endAddressDetail") String endAddressDetail, 
      @RequestParam(required = false, value = "endLat") Double endLat, 
      @RequestParam(required = false, value = "endLng") Double endLng, 
      @RequestParam(required = false, value = "budgetPay") Double budgetPay,
      @RequestParam(required = false, value = "preStartPrice") Double prestartPrice,
      @RequestParam(required = false, value = "preMileagePrice") Double premileagePrice,
      @RequestParam(required = false, value = "preRunTimePrice") Double prerunTimePrice,
      @RequestParam(required = false, value = "preTravelTime") Integer pretravelTime,
      @RequestParam(required = false, value = "preMileage") Double premileage,
      @RequestParam(required = false, value = "prePay") Boolean prePay,
      @RequestParam(required = false, value = "employId") Long employId,
      @RequestParam(required = false, value = "employName") String employName,
      @RequestParam(required = false, value = "employPhone") String employPhone,
      @RequestParam(required = false, value = "employCompanyId") Long employCompanyId, 
      @RequestParam(required = false, value = "employNo") String employNo,
      @RequestParam(required = false, value = "employPhoto") String employPhoto,
      @RequestParam(required = false, value = "employScore") Double employScore,
      @RequestParam(required = false, value = "couponId") Long couponId,
      @RequestParam(required = false, value = "shouldPay") Double shouldPay,
      @RequestParam(required = false, value = "operator") String operator,
      @RequestParam(required = false, value = "createOrderName") String createOrderName,
      @RequestParam("appKey") String appKey) {
    
    ResponseEntity<Object> responseEntity = null;
    appKey = StringUtils.trimToEmpty(appKey);
    Preconditions.checkArgument(StringUtils.isNotBlank(appKey), "AppKey不能为空");
    try {
      Map<String, Object> map = new HashMap<String, Object>();
      Order order = null;
      Date serverDate = new Date(serverTime);
        if (appKey.equals("154fb1999eb7499e8e5696693a416f3f")||appKey.equals("a05a1cf7990b4498a0b9c81b0d47d46c")) { //南航的系统
            Preconditions.checkArgument(StringUtils.isNotBlank(appKey), "当前APP版本过低，请升级后重试！");
        }
      CarType carType = carTypeManager.findByCarTypeId(carTypeId, appKey);
      if (null == carType) {
        Result<Map<String, Object>> result = new Result<Map<String, Object>>(
            ErrorConstantV4.ZHUAN_CARTYPE_NOT_EXISTS.getCode(),
            ErrorConstantV4.ZHUAN_CARTYPE_NOT_EXISTS.getMessage(), map);
        
        responseEntity = new ResponseEntity<Object>(result, HttpStatus.CREATED);
        return responseEntity;
      }

      if (prePay != null && prePay && (shouldPay != null && shouldPay > 0) 
          && !channelName.equals(Order.ORDER_TYPE_PHONE)) {
        // 需要预付费,下单到orderTemp表
        OrderTemp orderTemp =
            orderTempManager.insert(companyId, companyName, passengerId, passengerName,
                passengerPhone, showPhone, carTypeId, channelName, startAddress,
                startAddressDetail, startLat, startLng, endAddress, endAddressDetail, endLat,
                endLng, serverDate, prestartPrice, premileagePrice, prerunTimePrice, budgetPay,
                shouldPay, couponId, pretravelTime, premileage, createOrderName, appKey);

        map.put("id", orderTemp.getId());
        map.put("prePay", Boolean.TRUE);
        map.put("budgetPay", orderTemp.getBudgetPay());
      } else {
        // 不需要预付费 直接下单
        order =
            orderManager.insert(companyId, companyName, passengerId, passengerName, passengerPhone,
                showPhone, carTypeId, channelName, startAddress, startAddressDetail, startLat,
                startLng, endAddress, endAddressDetail, endLat, endLng, serverDate, prestartPrice,
                premileagePrice, prerunTimePrice, budgetPay, couponId, pretravelTime, premileage,
                operator, createOrderName, appKey);
        if (employId != null && employId != 0) {
          orderManager.updateStatus(order.getId(), employId, employName, employPhone,
              employCompanyId, employNo, employPhoto, employScore,null, null, "paidan", 
              passengerName, null, appKey);
        }
        map.put("id", order.getId());

        map.put("prePay", Boolean.FALSE);

        map.put("budgetPay", order.getBudgetPay());
      }
      Result<Map<String, Object>> result = new Result<Map<String, Object>>(0, "成功", map);

      responseEntity = new ResponseEntity<Object>(result, HttpStatus.CREATED);
      return responseEntity;
    } catch (Exception ex) {
      ex.printStackTrace();
      Error error = new Error(500, "服务器开小差了,请稍后再试");
      responseEntity = new ResponseEntity<Object>(error, HttpStatus.INTERNAL_SERVER_ERROR);
      return responseEntity;
    }

  }

  /**
   * 司机补单.
   * @param passengerId 客户id
   * @param passengerName 客户姓名
   * @param passengerPhone 客户电话
   * @param companyId 公司id
   * @param companyName 公司名称
   * @param carTypeId 车型id
   * @param channelName 订单渠道
   * @param startAddress 起点地址
   * @param startLat 起点纬度
   * @param startLng 起点经度
   * @param serverTime 服务时间
   * @param employId 服务人员id
   * @param employName 服务人员名称
   * @param employPhone 服务人员电话
   * @param employCompanyId 服务人员所属公司id
   * @param employNo 服务人员工号
   * @param employPhoto 服务人员头像
   * @param employScore 服务人员评分
   */
  
  @RequestMapping(value = "addmore", method = RequestMethod.POST)
  public ResponseEntity<Object> addmore(
      @RequestParam("passengerId") Long passengerId,
      @RequestParam("passengerName") String passengerName,
      @RequestParam("passengerPhone") String passengerPhone,
      @RequestParam("companyId") Long companyId, 
      @RequestParam("companyName") String companyName,
      @RequestParam("carTypeId") Long carTypeId, 
      @RequestParam("channelName") String channelName,
      @RequestParam("startAddress") String startAddress, 
      @RequestParam("startLat") Double startLat,
      @RequestParam("startLng") Double startLng,
      @RequestParam("serverTime") Long serverTime,
      @RequestParam(required = false, value = "employId") Long employId,
      @RequestParam(required = false, value = "employName") String employName,
      @RequestParam(required = false, value = "employPhone") String employPhone, 
      @RequestParam(required = false, value = "employCompanyId") Long employCompanyId, 
      @RequestParam(required = false, value = "employNo") String employNo, 
      @RequestParam(required = false, value = "employPhoto") String employPhoto, 
      @RequestParam(required = false, value = "employScore") Double employScore,
      @RequestParam(required = false, value = "memo") String memo,
      @RequestParam("appKey") String appKey) {
    ResponseEntity<Object> responseEntity = null;
    appKey = StringUtils.trimToEmpty(appKey);
    Preconditions.checkArgument(StringUtils.isNotBlank(appKey), "AppKey不能为空");
    try {
      Map<String, Object> map = new HashMap<String, Object>();
      Date serverDate = new Date(serverTime);
        if (appKey.equals("154fb1999eb7499e8e5696693a416f3f")||appKey.equals("a05a1cf7990b4498a0b9c81b0d47d46c")) { //南航的系统
            Preconditions.checkArgument(StringUtils.isNotBlank(appKey), "当前APP版本过低，请升级后重试！");
        }
      Order order =
          orderManager.addmore(passengerId, passengerName, passengerPhone, companyId, companyName,
              carTypeId, channelName, startAddress, startLat, startLng, serverDate, employId,
              employName, employPhone, employCompanyId, employNo, employPhoto, employScore, memo,
              appKey);
      map.put("id", order.getId());
      Result<Map<String, Object>> result = new Result<Map<String, Object>>(0, "成功", map);

      responseEntity = new ResponseEntity<Object>(result, HttpStatus.CREATED);
      return responseEntity;
    } catch (Exception ex) {
      ex.printStackTrace();
      Error error = new Error(500, "内部服务器错误：" + ex.getMessage());
      responseEntity = new ResponseEntity<Object>(error, HttpStatus.INTERNAL_SERVER_ERROR);
      return responseEntity;
    }

  }

  /**
   * 查询某个人最后一个结算的订单.
   * @param passengerId 客户id
   */
  
  @RequestMapping(value = {"findLastOrder"}, method = RequestMethod.GET)
  public ResponseEntity<Object> findLastOrder(
      @RequestParam("passengerId") Long passengerId,
      @RequestParam("appKey") String appKey) {
    ResponseEntity<Object> responseEntity = null;
    appKey = StringUtils.trimToEmpty(appKey);
    Preconditions.checkArgument(StringUtils.isNotBlank(appKey), "AppKey不能为空");
    try {
      OrderQuery orderQuery = new OrderQuery();
      orderQuery.setPassengerId(passengerId);
      orderQuery.setStatusArray("5");
      orderQuery.setAppKey(appKey);
      
      Order order = orderManager.findLastOrder(orderQuery);

      Result<Order> result = new Result<Order>(0, "成功", order);

      responseEntity = new ResponseEntity<Object>(result, HttpStatus.OK);

      return responseEntity;
    } catch (Exception ex) {
      ex.printStackTrace();
      Error error = new Error(500, "内部服务器错误：" + ex.getMessage());

      responseEntity = new ResponseEntity<Object>(error, HttpStatus.INTERNAL_SERVER_ERROR);

      return responseEntity;
    }
  }

  /**
   * 多条件分页查询订单.
   * @param companyId 公司id
   * @param companyName 公司名称
   * @param orderNo 订单号
   * @param employId 服务人员id
   * @param employName 服务人员姓名
   * @param employPhone 服务人员电话
   * @param passengerId 客户id
   * @param passengerName 客户姓名
   * @param passengerPhone 客户电话
   * @param carNumber 车牌号
   * @param status 状态
   * @param allorderType 订单来源字符串(以,隔开)
   * @param allstatus 订单状态字符串(以,隔开)
   * @param orderby 查询排序字符串
   * @param page 分页参数
   * @param rows 分页参数
   * @param startTime 订单创建时间:开始时间
   * @param endTime 订单创建时间:结束时间
   * @param treatment 未支付
   * @param startFinishTime 订单完成时间:开始时间
   * @param endFinishTime 订单完成时间:结束时间
   */
  @RequestMapping(value = {"", "/"}, method = RequestMethod.GET)
  public ResponseEntity<Object> findByParams(
      @RequestParam(required = false, value = "companyId") Long companyId,
      @RequestParam(required = false, value = "companyName") String companyName, 
      @RequestParam(required = false, value = "orderNo") String orderNo,
      @RequestParam(required = false, value = "employId") Long employId,
      @RequestParam(required = false, value = "employName") String employName, 
      @RequestParam(required = false, value = "employPhone") String employPhone, 
      @RequestParam(required = false, value = "passengerId") Long passengerId,
      @RequestParam(required = false, value = "passengerName") String passengerName,
      @RequestParam(required = false, value = "passengerPhone") String passengerPhone,
      @RequestParam(required = false, value = "carNumber") String carNumber,
      @RequestParam(required = false, value = "status") String status,
      @RequestParam(required = false, value = "allorderType") String allorderType,
      @RequestParam(required = false, value = "allstatus") String allstatus,
      @RequestParam(required = false, value = "orderby") String orderby,
      @RequestParam(required = false, value = "page") Integer page,
      @RequestParam(required = false, value = "rows") Integer rows,
      @RequestParam(required = false, value = "startTime") Long startTime,
      @RequestParam(required = false, value = "endTime") Long endTime,
      @RequestParam(required = false, value = "treatment") Boolean treatment,
      @RequestParam(required = false, value = "review") Boolean review,
      @RequestParam(required = false, value = "startFinishTime") Long startFinishTime,
      @RequestParam(required = false, value = "endFinishTime") Long endFinishTime,
      @RequestParam(required = false, value = "createOrderName") String createOrderName,
      @RequestParam(required = false, value = "paid") Boolean paid,
      @RequestParam("appKey") String appKey) {
    ResponseEntity<Object> responseEntity = null;
    appKey = StringUtils.trimToEmpty(appKey);
    Preconditions.checkArgument(StringUtils.isNotBlank(appKey), "AppKey不能为空");
    try {
      OrderQuery orderQuery = new OrderQuery();
      
      orderQuery.setCompanyId(companyId);
      orderQuery.setCompanyName(companyName);
      orderQuery.setOrderNo(orderNo);
      orderQuery.setEmployId(employId);
      orderQuery.setEmployNameOrPhone(employName);
      orderQuery.setEmployPhone(employPhone);
      orderQuery.setPassengerId(passengerId);
      orderQuery.setPassengerNameOrPhone(passengerName);
      orderQuery.setPassengerPhone(passengerPhone);
      orderQuery.setCarNumber(carNumber);
      orderQuery.setChannelNameArray(allorderType);
      orderQuery.setOrderby(orderby);
      orderQuery.setPage(page);
      orderQuery.setRows(rows);
      orderQuery.setStartTime(startTime);
      orderQuery.setEndTime(endTime);
      orderQuery.setStatusArray(status);
      orderQuery.setStatusArray(allstatus);
      if (treatment != null && treatment) { // 选中"未支付选项"时,查询已确认费用的订单
        if (StringUtils.isBlank(allstatus)) {
          orderQuery.setStatusArray("4");
          orderQuery.setTreatment(treatment);
        }
      }
      if (null != paid && !paid) { //查询未支付的订单,不查询出未支付订单
        orderQuery.setTreatment(false);
      }
      orderQuery.setReview(review);
      orderQuery.setStartFinishTime(startFinishTime);
      orderQuery.setEndFinishTime(endFinishTime);
      orderQuery.setCreateOrderName(createOrderName);
      orderQuery.setAppKey(appKey);
      
      DataGrid<Order> dataGrid = orderManager.findByParams(orderQuery);

      Result<DataGrid<Order>> result = new Result<DataGrid<Order>>(0, "成功", dataGrid);

      responseEntity = new ResponseEntity<Object>(result, HttpStatus.OK);

      return responseEntity;

    } catch (Exception ex) {
      ex.printStackTrace();
      Error error = new Error(500, "内部服务器错误：" + ex.getMessage());

      responseEntity = new ResponseEntity<Object>(error, HttpStatus.INTERNAL_SERVER_ERROR);

      return responseEntity;
    }

  }
  
  
  /**
   * 查询预约订单 
   * @param page 页码
   * @param rows 行数
   * @param latitude 纬度	
   * @param longitude 经度
   * @param carTypeId 当前司机车型Id
   * @param appKey 系统
   * @return
   */
  @RequestMapping(value = {"findByParamsInBook"}, method = RequestMethod.GET)
  public ResponseEntity<Object> findByParamsInBook(
      @RequestParam(required = false, value = "page") Integer page,
      @RequestParam(required = false, value = "rows") Integer rows,
      @RequestParam(required = false, value = "latitude") Double latitude,
      @RequestParam(required = false, value = "longitude") Double longitude,
      @RequestParam(required = false, value = "carTypeId") Integer carTypeId,
      @RequestParam(required = false, value = "serverUrl") String serverUrl,// 代驾项目服务器地址
      @RequestParam("appKey") String appKey) {
    ResponseEntity<Object> responseEntity = null;
    appKey = StringUtils.trimToEmpty(appKey);
    Preconditions.checkArgument(StringUtils.isNotBlank(appKey), "AppKey不能为空");
    try {
      OrderQuery orderQuery = new OrderQuery();
      
      RestTemplate restTemplate = new RestTemplate();
      JSONObject yuyueSetting = daijiaApi.getYuyueSetting(serverUrl);
      
      List<CarTypeRel> carTypeRels = carTypeManager.findByCarTypeRelBycarTypeId(carTypeId.longValue(), appKey);
      List<Integer> carTypeIds = new ArrayList<Integer>();
      if (null != carTypeRels) {
    	  for (CarTypeRel carTypeRel : carTypeRels) {
    		  carTypeIds.add(Integer.valueOf(carTypeRel.getAccessibleType()));
    	  };
      }
      
      carTypeIds.add(carTypeId);
      orderQuery.setCarTypeIds(carTypeIds);
      
      orderQuery.setPage(page);
      orderQuery.setRows(rows);
//      orderQuery.setCarTypeId(carTypeId);
      orderQuery.setAppKey(appKey);
      orderQuery.setDriverLatitude(latitude);
      orderQuery.setDriverLongitude(longitude);
      Long now = new Date().getTime();
      Long TimeYuyue = yuyueSetting.getInteger("zhuanYuyue").longValue();
      //加上后台设置时间
//      Date yuyueTime = new Date(now + TimeYuyue*60*1000);
      //不加上后台设置时间
      Date yuyueTime = new Date(now);
      orderQuery.setYuyueTime(yuyueTime);
      
      DataGrid<Order> dataGrid = orderManager.findByParamsInBook(orderQuery);

      Result<DataGrid<Order>> result = new Result<DataGrid<Order>>(0, "成功", dataGrid);

      responseEntity = new ResponseEntity<Object>(result, HttpStatus.OK);

      return responseEntity;

    } catch (Exception ex) {
      ex.printStackTrace();
      Error error = new Error(500, "内部服务器错误：" + ex.getMessage());

      responseEntity = new ResponseEntity<Object>(error, HttpStatus.INTERNAL_SERVER_ERROR);

      return responseEntity;
    }

  }
  
  /**
   * 查询预约订单 
   * @param page
   * @param rows
   * @param latitude
   * @param longitude
   * @param carTypeId
   * @param appKey
   * @return
   */
  @RequestMapping(value = {"countByParamsInBook"}, method = RequestMethod.GET)
  public ResponseEntity<Object> countByParamsInBook(
      @RequestParam(required = false, value = "latitude") Double latitude,
      @RequestParam(required = false, value = "longitude") Double longitude,
      @RequestParam(required = false, value = "carTypeId") Integer carTypeId,
      @RequestParam(required = false, value = "serverUrl") String serverUrl,// 代驾项目服务器地址
      @RequestParam("appKey") String appKey) {
    ResponseEntity<Object> responseEntity = null;
    appKey = StringUtils.trimToEmpty(appKey);
    Preconditions.checkArgument(StringUtils.isNotBlank(appKey), "AppKey不能为空");
    try {
      OrderQuery orderQuery = new OrderQuery();
      
      RestTemplate restTemplate = new RestTemplate(); 
   
      JSONObject yuyueSetting =  daijiaApi.getYuyueSetting(serverUrl);
      
      List<CarTypeRel> carTypeRels = carTypeManager.findByCarTypeRelBycarTypeId(carTypeId.longValue(), appKey);
      List<Integer> carTypeIds = new ArrayList<Integer>();
      if (null != carTypeRels) {
    	  for (CarTypeRel carTypeRel : carTypeRels) {
    		  carTypeIds.add(Integer.valueOf(carTypeRel.getAccessibleType()));
    	  };
      }
      
      carTypeIds.add(carTypeId);
      orderQuery.setCarTypeIds(carTypeIds);
      
//      orderQuery.setCarTypeId(carTypeId);
      orderQuery.setAppKey(appKey);
      orderQuery.setDriverLatitude(latitude);
      orderQuery.setDriverLongitude(longitude); 
      Long now = new Date().getTime();
      Long TimeYuyue = yuyueSetting.getInteger("zhuanYuyue").longValue();
      //加上后台设置时间
      //    Date yuyueTime = new Date(now + TimeYuyue*60*1000);
      //不加上后台设置时间
      Date yuyueTime = new Date(now);
      orderQuery.setYuyueTime(yuyueTime);
      Long totals = orderManager.countByParamsInBook(orderQuery);

      Result<Long> result = new Result<Long>(0, "成功", totals);

      responseEntity = new ResponseEntity<Object>(result, HttpStatus.OK);

      return responseEntity;

    } catch (Exception ex) {
      ex.printStackTrace();
      Error error = new Error(500, "内部服务器错误：" + ex.getMessage());

      responseEntity = new ResponseEntity<Object>(error, HttpStatus.INTERNAL_SERVER_ERROR);

      return responseEntity;
    }

  }
  
  /**
   * 后台查询订单列表接口.
   */
  @RequestMapping(value = {"queryOrders"}, method = RequestMethod.GET)
  public ResponseEntity<Object> queryOrders(
      @RequestParam(required = false, value = "companyId") Long companyId,
      @RequestParam(required = false, value = "companyName") String companyName, 
      @RequestParam(required = false, value = "rentalCompanyId") Long rentalCompanyId, 
      @RequestParam(required = false, value = "rentalCompanyName") String rentalCompanyName, 
      @RequestParam(required = false, value = "orderNo") String orderNo,
      @RequestParam(required = false, value = "employId") Long employId,
      @RequestParam(required = false, value = "employName") String employName, 
      @RequestParam(required = false, value = "employPhone") String employPhone, 
      @RequestParam(required = false, value = "passengerId") Long passengerId,
      @RequestParam(required = false, value = "passengerName") String passengerName,
      @RequestParam(required = false, value = "passengerPhone") String passengerPhone,
      @RequestParam(required = false, value = "carNumber") String carNumber,
      @RequestParam(required = false, value = "status") String status,
      @RequestParam(required = false, value = "allorderType") String allorderType,
      @RequestParam(required = false, value = "allstatus") String allstatus,
      @RequestParam(required = false, value = "orderby") String orderby,
      @RequestParam(required = false, value = "page") Integer page,
      @RequestParam(required = false, value = "rows") Integer rows,
      @RequestParam(required = false, value = "startTime") Long startTime,
      @RequestParam(required = false, value = "endTime") Long endTime,
      @RequestParam(required = false, value = "treatment") Boolean treatment,
      @RequestParam(required = false, value = "startFinishTime") Long startFinishTime,
      @RequestParam(required = false, value = "endFinishTime") Long endFinishTime,
      @RequestParam(required = false, value = "startTreatmentTime") Long startTreatmentTime,
      @RequestParam(required = false, value = "endTreatmentTime") Long endTreatmentTime,
      @RequestParam(required = false, value = "createOrderName") String createOrderName,
      @RequestParam("appKey") String appKey) {
    ResponseEntity<Object> responseEntity = null;
    appKey = StringUtils.trimToEmpty(appKey);
    Preconditions.checkArgument(StringUtils.isNotBlank(appKey), "AppKey不能为空");
    try {
      OrderQuery orderQuery = new OrderQuery();
      
      orderQuery.setCompanyId(companyId);
      orderQuery.setCompanyName(companyName);
      orderQuery.setRentalCompanyId(rentalCompanyId);
      orderQuery.setRentalCompanyName(rentalCompanyName);
      orderQuery.setOrderNo(orderNo);
      orderQuery.setEmployId(employId);
      orderQuery.setEmployNameOrPhone(employName);
      orderQuery.setEmployPhone(employPhone);
      orderQuery.setPassengerId(passengerId);
      orderQuery.setPassengerNameOrPhone(passengerName);
      orderQuery.setPassengerPhone(passengerPhone);
      orderQuery.setCarNumber(carNumber);
      orderQuery.setChannelNameArray(allorderType);
      orderQuery.setOrderby(orderby);
      orderQuery.setPage(page);
      orderQuery.setRows(rows);
      orderQuery.setStartTime(startTime);
      orderQuery.setEndTime(endTime);
      orderQuery.setStatusArray(status);
      orderQuery.setStatusArray(allstatus);
      if (treatment != null && treatment) { // 选中"未支付选项"时,查询已确认费用的订单
        if (StringUtils.isBlank(status) && StringUtils.isBlank(allstatus)) {
          orderQuery.setStatusStr("nopay");
          orderQuery.setTreatment(Boolean.TRUE);
        } else {
          if (allstatus.equals("5")) { //选中"已完成"和"未支付"
            orderQuery.setStatusStr("nopayandfinish");
            orderQuery.setTreatment(Boolean.TRUE);
          } else { //选中"未支付"和"执行中,已派单..."
            orderQuery.setStatusArray(allstatus+",4");
          }
        }
      }
      orderQuery.setStartFinishTime(startFinishTime);
      orderQuery.setEndFinishTime(endFinishTime);
      if (null != startTreatmentTime) {
        orderQuery.setStartTreatmentTime(new Date(startTreatmentTime));
      }
      if (null != endTreatmentTime) {
        orderQuery.setEndTreatmentTime(new Date(endTreatmentTime));
      }
      
      orderQuery.setCreateOrderName(createOrderName);
      orderQuery.setAppKey(appKey);
      
      DataGrid<Order> dataGrid = orderManager.queryOrders(orderQuery);
      
      Result<DataGrid<Order>> result = new Result<DataGrid<Order>>(0, "成功", dataGrid);
      
      responseEntity = new ResponseEntity<Object>(result, HttpStatus.OK);
      
      return responseEntity;
      
    } catch (Exception ex) {
      ex.printStackTrace();
      Error error = new Error(500, "内部服务器错误：" + ex.getMessage());
      
      responseEntity = new ResponseEntity<Object>(error, HttpStatus.INTERNAL_SERVER_ERROR);
      
      return responseEntity;
    }
    
  }

    /**
     *  通过司机工号查询完成单量
     */
    @RequestMapping(value = {"orderCountByEmployId"}, method = RequestMethod.GET)
    public ResponseEntity<Object> orderCountByEmployId(
            @RequestParam(required = false, value = "employId") Long employId,
            @RequestParam(required = false, value = "status") String status,
            @RequestParam(required = false, value = "allstatus") String allstatus,
            @RequestParam(required = false, value = "treatment") Boolean treatment,
            @RequestParam("appKey") String appKey) {
        ResponseEntity<Object> responseEntity = null;
        appKey = StringUtils.trimToEmpty(appKey);
        Preconditions.checkArgument(StringUtils.isNotBlank(appKey), "AppKey不能为空");
        try {
            OrderQuery orderQuery = new OrderQuery();
            orderQuery.setEmployId(employId);
            orderQuery.setStatusArray(status);
            orderQuery.setStatusArray(allstatus);
            if (treatment != null && treatment) { // 选中"未支付选项"时,查询已确认费用的订单
                if (StringUtils.isBlank(status) && StringUtils.isBlank(allstatus)) {
                    orderQuery.setStatusStr("nopay");
                    orderQuery.setTreatment(Boolean.TRUE);
                } else {
                    if (allstatus.equals("5")) { //选中"已完成"和"未支付"
                        orderQuery.setStatusStr("nopayandfinish");
                        orderQuery.setTreatment(Boolean.TRUE);
                    } else { //选中"未支付"和"执行中,已派单..."
                        orderQuery.setStatusArray(allstatus+",4");
                    }
                }
            }

            orderQuery.setAppKey(appKey);

            Long count = orderManager.orderCountByEmployId(orderQuery);

            Result<Long> result = new Result<Long>(0, "成功", count);

            responseEntity = new ResponseEntity<Object>(result, HttpStatus.OK);

            return responseEntity;

        } catch (Exception ex) {
            ex.printStackTrace();
            Error error = new Error(500, "内部服务器错误：" + ex.getMessage());

            responseEntity = new ResponseEntity<Object>(error, HttpStatus.INTERNAL_SERVER_ERROR);

            return responseEntity;
        }

    }
  
  
  /**
   * 查询指定客户执行中的订单(状态1,2,3,4).
   * @param passengerId 客户id
   */
  
  @RequestMapping(value = {"queryRunOrder"}, method = RequestMethod.GET)
  public ResponseEntity<Object> queryRunOrder(
      @RequestParam("passengerId") Long passengerId,
      @RequestParam("appKey") String appKey) {
    ResponseEntity<Object> responseEntity = null;
    appKey = StringUtils.trimToEmpty(appKey);
    Preconditions.checkArgument(StringUtils.isNotBlank(appKey), "AppKey不能为空");
    try {
      OrderQuery orderQuery = new OrderQuery();
        
      orderQuery.setPassengerId(passengerId);
      orderQuery.setStatusArray("1,2,3,4");
      orderQuery.setAppKey(appKey);
      Long count = orderManager.queryRunOrder(orderQuery);

      Result<Long> result = new Result<Long>(0, "成功", count);

      responseEntity = new ResponseEntity<Object>(result, HttpStatus.OK);

      return responseEntity;

    } catch (Exception ex) {
      ex.printStackTrace();
      Error error = new Error(500, "内部服务器错误：" + ex.getMessage());

      responseEntity = new ResponseEntity<Object>(error, HttpStatus.INTERNAL_SERVER_ERROR);

      return responseEntity;
    }

  }

  /**
   * 根据乘客id,完成时间段,查询订单数量.
   * @param passengerId 客户id
   * @param startTime 完成订单时间段起点
   * @param endTime 完成订单时间段终点
   * @param orderFromSources 订单来源
   * @return 订单数量 count
   */
  
  @RequestMapping(value = {"countByParam"}, method = RequestMethod.GET)
  public ResponseEntity<Object> countByParam(
      @RequestParam("passengerId") Long passengerId,
      @RequestParam("startTime") Long startTime,
      @RequestParam(required = false, value = "endTime") Long endTime,
      @RequestParam(required = false, value = "orderFromSources") String orderFromSources,
      @RequestParam("appKey") String appKey) {
    ResponseEntity<Object> responseEntity = null;
    appKey = StringUtils.trimToEmpty(appKey);
    Preconditions.checkArgument(StringUtils.isNotBlank(appKey), "AppKey不能为空");
    try {
      OrderQuery orderQuery = new OrderQuery();
      orderQuery.setPassengerId(passengerId);
      orderQuery.setStartFinishTime(startTime);
      orderQuery.setAppKey(appKey);
      orderQuery.setStatusArray("5");
      if (endTime != null) {
        orderQuery.setEndFinishTime(endTime);
      }
      if (StringUtils.isNotBlank(orderFromSources)) {
        orderQuery.setChannelNameArray(orderFromSources);
      }
      
      Long count = orderManager.countByParam(orderQuery);
      
      Result<Long> result = new Result<Long>(0, "成功", count);

      responseEntity = new ResponseEntity<Object>(result, HttpStatus.OK);

      return responseEntity;

    } catch (Exception ex) {
      ex.printStackTrace();
      Error error = new Error(500, "内部服务器错误：" + ex.getMessage());

      responseEntity = new ResponseEntity<Object>(error, HttpStatus.INTERNAL_SERVER_ERROR);

      return responseEntity;
    }

  }

  /**
   * 查询单个订单.
   * @param id 订单id
   */
  
  @RequestMapping(value = "findByOrderId", method = RequestMethod.GET)
  public ResponseEntity<Object> findByOrderId(
      @RequestParam("orderId") Long id,
      @RequestParam("appKey") String appKey) {
    ResponseEntity<Object> responseEntity = null;
    Preconditions.checkArgument(StringUtils.isNotBlank(appKey), "AppKey不能为空");
    Preconditions.checkArgument(id != null, "订单id不能为空");
    try {
      Order order = orderManager.findByIdAndAppKey(id, appKey);

      // 获取是否是出租车车型
      Long carTypeId = order.getCarTypeId();
	  CarType carType = carTypeManager.findByCarTypeId(carTypeId, appKey);
      String ifTaxi = "0";
      if (null != carType) {
          ifTaxi = carType.getIfTaxi();
      }
      order.setIfTaxi(ifTaxi);

      Result<Order> result = new Result<Order>(0, "成功", order);
      responseEntity = new ResponseEntity<Object>(result, HttpStatus.OK);
      return responseEntity;
    } catch (Exception ex) {
      ex.printStackTrace();
      Error error = new Error(500, "内部服务器错误：" + ex.getMessage());
      responseEntity = new ResponseEntity<Object>(error, HttpStatus.INTERNAL_SERVER_ERROR);
      return responseEntity;
    }
  }

  /**
   * 查询订单轨迹.
   * @param orderId 订单id
   */
  @RequestMapping(value = "findOrderOrbit", method = RequestMethod.GET)
  public ResponseEntity<Object> findOrderOrbit(
      @RequestParam("orderId") Long orderId,
      @RequestParam("appKey") String appKey) {
    ResponseEntity<Object> responseEntity = null;
    Preconditions.checkArgument(StringUtils.isNotBlank(appKey), "AppKey不能为空");
    Preconditions.checkArgument(orderId != null, "订单id不能为空");
    try {
      OrderOrbit orderOrbit = orderOrbitManager.findByOrderId(orderId);
      Result<OrderOrbit> result = new Result<OrderOrbit>(0, "成功", orderOrbit);
      responseEntity = new ResponseEntity<Object>(result, HttpStatus.OK);
      return responseEntity;
    } catch (Exception ex) {
      ex.printStackTrace();
      Error error = new Error(500, "内部服务器错误：" + ex.getMessage());
      responseEntity = new ResponseEntity<Object>(error, HttpStatus.INTERNAL_SERVER_ERROR);
      return responseEntity;
    }
  }

  /**
   * 根据订单id查询拒单记录.
   * @param orderId 订单id
   */
  
  @RequestMapping(value = "findOrderRefuse", method = RequestMethod.GET)
  public ResponseEntity<Object> findOrderRefuse(
      @RequestParam("orderId") Long orderId,
      @RequestParam("appKey") String appKey) {
    ResponseEntity<Object> responseEntity = null;
    Preconditions.checkArgument(StringUtils.isNotBlank(appKey), "AppKey不能为空");
    Preconditions.checkArgument(orderId != null, "订单id不能为空");
    try {
      Order order = orderManager.findByIdAndAppKey(orderId, appKey);
      Result<Order> result = new Result<Order>(0, "成功", order);
      responseEntity = new ResponseEntity<Object>(result, HttpStatus.OK);
      return responseEntity;
    } catch (Exception ex) {
      ex.printStackTrace();
      Error error = new Error(500, "内部服务器错误：" + ex.getMessage());
      responseEntity = new ResponseEntity<Object>(error, HttpStatus.INTERNAL_SERVER_ERROR);
      return responseEntity;
    }
  }
  /**
   * 后台直接销单.
   * @param orderId 订单id
   * @param operator 操作人
   * @param cause 原因
   */
  
  @RequestMapping(value = "cancel", method = RequestMethod.PUT)
  public ResponseEntity<Object> updateStatus(
      @RequestParam("orderId") Long orderId,
      @RequestParam("operator") String operator, 
      @RequestParam("cause") String cause,
      @RequestParam(required = false,value="breaker")Integer breaker,
      @RequestParam("appKey") String appKey) {
    ResponseEntity<Object> responseEntity = null;
    appKey = StringUtils.trimToEmpty(appKey);
    Order order = null;
    try {
      order = orderManager.findByIdAndAppKey(orderId, appKey);
     /* if(order.getStatus().intValue()>=2){
        Error error = new Error(-1, "请填写违约方");
        responseEntity = new ResponseEntity<Object>(error, HttpStatus.INTERNAL_SERVER_ERROR);
        return responseEntity;
      }*/
      orderManager.cancelOrder(orderId, operator,breaker, cause, appKey);

      Result<Order> result = new Result<Order>(0, "成功", order);

      responseEntity = new ResponseEntity<Object>(result, HttpStatus.CREATED);

      return responseEntity;
    } catch (Exception ex) {

      ex.printStackTrace();
      Error error = new Error(500, "内部服务器错误：" + ex.getMessage());
      responseEntity = new ResponseEntity<Object>(error, HttpStatus.INTERNAL_SERVER_ERROR);
      return responseEntity;
    }
  }
  /**
   * 修改订单状态.
   * @param orderId 订单id
   * @param employId 服务人员id
   * @param employName 服务人员姓名
   * @param employPhone 服务人员电话
   * @param employCompanyId 服务人员所属公司id
   * @param action 派单:paidan 接单:jiedan 到达目的地开始等待:wait 出发:run 销单:cancel 收回:callback
   * @param operator 操作人
   * @param cause 原因
   */
  
  @RequestMapping(value = "update", method = RequestMethod.PUT)
  public ResponseEntity<Object> updateStatus(
      @RequestParam("orderId") Long orderId, 
      @RequestParam(required = false, value = "employId") Long employId,
      @RequestParam(required = false, value = "employName") String employName,
      @RequestParam(required = false, value = "employPhone") String employPhone,
      @RequestParam(required = false, value = "employCompanyId") Long employCompanyId, 
      @RequestParam(required = false, value = "employNo") String employNo,
      @RequestParam(required = false, value = "employPhoto") String employPhoto,
      @RequestParam(required = false, value = "employScore") Double employScore,
      @RequestParam(required = false, value = "rentalCompanyId") Long rentalCompanyId,
      @RequestParam(required = false, value = "rentalCompanyName") String rentalCompanyName,
      @RequestParam("action") String action,
      @RequestParam("operator") String operator,
      @RequestParam(required = false, value = "cause") String cause,
      @RequestParam("appKey") String appKey) {
    try {
      appKey = StringUtils.trimToEmpty(appKey);
      Preconditions.checkArgument(StringUtils.isNotBlank(appKey), "AppKey不能为空");

      Order order = orderManager.findByIdAndAppKey(orderId, appKey);
      Preconditions.checkArgument(order != null, "订单不存在");
      if ("paidan".equals(action)) {
        Preconditions.checkArgument(order.getStatus() == 0, "订单状态不正确");
        Preconditions.checkArgument(employId != null && employId != 0, "司机Id不正确");
        Preconditions.checkArgument(StringUtils.isNotBlank(employName), "司机名字不能 为空");
        Preconditions.checkArgument(StringUtils.isNotBlank(employPhone), "司机电话不能 为空");
        Preconditions
            .checkArgument(employCompanyId != null && employCompanyId != 0, "司机所属的公司Id不正确");
      } else if ("jiedan".equals(action)) {
        Preconditions.checkArgument(employId != null && employId != 0, "司机Id不正确");
        Preconditions.checkArgument(StringUtils.isNotBlank(employName), "司机名字不能 为空");
        Preconditions.checkArgument(StringUtils.isNotBlank(employPhone), "司机电话不能 为空");
      } else if ("refuse".equals(action)) {
        Preconditions.checkArgument(order.getStatus() == 1, "订单状态不正确");
        Preconditions.checkArgument(StringUtils.isNotBlank(cause), "拒接订单原因不能为空");
        Preconditions.checkArgument(employId != null && employId != 0, "司机Id不正确");
      } else if ("callback".equals(action)) {
        Preconditions.checkArgument(order.getStatus() != 4, "订单状态不正确");
        Preconditions.checkArgument(order.getStatus() != 5, "订单状态不正确");
      } else if ("wait".equals(action)) {
        Preconditions.checkArgument(order.getStatus() == 2, "订单状态不正确");
      } else if ("run".equals(action)) {
        Preconditions.checkArgument(order.getStatus() == 3, "订单状态不正确");
      } else if ("cancel".equals(action)) {
        Preconditions.checkArgument(order.getStatus() < 4, "订单状态不正确");
        Preconditions.checkArgument(StringUtils.isNotBlank(cause), "销单原因不能为空");
      }

      orderManager.updateStatus(
          orderId, employId, employName, employPhone, employCompanyId, employNo, employPhoto,
          employScore, rentalCompanyId, rentalCompanyName, action, operator, cause, appKey);

      Result<Order> result = new Result<Order>(0, "成功", order);
      
      ResponseEntity<Object> responseEntity = null;

      responseEntity = new ResponseEntity<Object>(result, HttpStatus.CREATED);

      return responseEntity;
    } catch (Exception ex) {
      ex.printStackTrace();
      Error error = new Error(500, "内部服务器错误：" + ex.getMessage());
      return new ResponseEntity<Object>(error, HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }

  /**
   * 后台自动派单.
   */
  @RequestMapping(value = "autoPaidan", method = RequestMethod.PUT)
  public ResponseEntity<Object> autoPaidan(
      @RequestParam("orderId") Long orderId, 
      @RequestParam("employId") Long employId,
      @RequestParam("employName") String employName,
      @RequestParam("employPhone") String employPhone,
      @RequestParam("employNo") String employNo,
      @RequestParam("employPhoto") String employPhoto,
      @RequestParam("employScore") Double employScore,
      @RequestParam("employCompanyId") Long employCompanyId, 
      @RequestParam(required = false, value = "rentalCompanyId") Long rentalCompanyId,
      @RequestParam(required = false, value = "rentalCompanyName") String rentalCompanyName,
      @RequestParam("appKey") String appKey) {
    ResponseEntity<Object> responseEntity = null;
    appKey = StringUtils.trimToEmpty(appKey);
    try {
      Order order = orderManager.queryOneOrder(orderId, appKey);

      
      orderManager.autoPaidan(orderId, employId, employName, employPhone,
          employCompanyId, employNo, employPhoto, employScore,
          rentalCompanyId, rentalCompanyName, appKey);

      Result<Order> result = new Result<Order>(0, "成功", order);

      responseEntity = new ResponseEntity<Object>(result, HttpStatus.CREATED);

      return responseEntity;
    } catch (Exception ex) {

      ex.printStackTrace();
      Error error = new Error(500, "内部服务器错误：" + ex.getMessage());
      responseEntity = new ResponseEntity<Object>(error, HttpStatus.INTERNAL_SERVER_ERROR);
      return responseEntity;
    }
  }
  


  /**
   * 确认订单结算信息.
   * @param orderId 订单Id
   * @param realPay 总金额
   * @param guoluMoney 过路金额
   * @param yuanchengMoney 远程金额
   * @param otherMoney 其它金额
   * @param startPrice 实际起步价
   * @param mileagePrice 实际的里程费
   * @param runTimePrice 实际的时间费用
   * @param endAddress 目的地(中途修改过的)
   * @param endLat 目的地纬度
   * @param endLng 目的地经度
   * @param mileage 实际里程
   * @param midwayWait 等候时间总和
   * @param runTime 实际执行时间(分钟)
   * @param xml 保单数据(暂无)
   */
  
  @RequestMapping(value = "confirmTask", method = RequestMethod.POST)
  public ResponseEntity<Object> completeTask(
      @RequestParam("orderId") Long orderId,
      @RequestParam("realPay") Double realPay,
      @RequestParam("startPrice") Double startPrice,
      @RequestParam("mileagePrice") Double mileagePrice,
      @RequestParam("runTimePrice") Double runTimePrice, 
      @RequestParam("mileage") Double mileage, 
      @RequestParam("midwayWait") Integer midwayWait,
      @RequestParam("runTime") Integer runTime,
      @RequestParam(required = false, value = "guoluMoney") Double guoluMoney, 
      @RequestParam(required = false, value = "yuanchengMoney") Double yuanchengMoney, 
      @RequestParam(required = false, value = "otherMoney") Double otherMoney,
      @RequestParam(required = false, value = "waitPrice") Double waitPrice, 
      @RequestParam(required = false, value = "endAddress") String endAddress,
      @RequestParam(required = false, value = "endLat") Double endLat,
      @RequestParam(required = false, value = "endLng") Double endLng,
      @RequestParam(required = false, value = "xml") String xml,
      @RequestParam(required = false,value = "couponMoney") Double couponMoney,// 优惠券金额
      @RequestParam(required = false, value = "discount") Double discount, // 优惠券折扣
      @RequestParam(required = false, value = "prePayTypeDetail") String prePayTypeDetail, // 预支付类型
      @RequestParam(required = false, value = "memo") String memo, //备注
      @RequestParam(required = false, value = "justKilometres") Double justKilometres,
      @RequestParam(required = false, value = "justMoney") BigDecimal justMoney,
      @RequestParam(required = false, value = "ksMileage") Double ksMileage,
      @RequestParam(required = false, value = "ddMileage") Double ddMileage,
      @RequestParam("appKey") String appKey) {
    ResponseEntity<Object> responseEntity = null;
    appKey = StringUtils.trimToEmpty(appKey);
    Preconditions.checkArgument(StringUtils.isNotBlank(appKey), "AppKey不能为空");
    Order order = null;

    try {
      order =
          orderManager.complete(orderId, realPay, guoluMoney, yuanchengMoney, otherMoney,
              startPrice, mileagePrice, runTimePrice, waitPrice, endAddress, endLat, endLng,
              mileage, midwayWait, runTime, couponMoney, appKey, prePayTypeDetail, memo,
              justKilometres,justMoney, ksMileage, ddMileage);
      if (StringUtils.isNotBlank(xml)) {
        orderOrbitManager.insert(orderId, xml);
      }
      Result<Order> result = new Result<Order>(0, "成功", order);
      responseEntity = new ResponseEntity<Object>(result, HttpStatus.CREATED);

      return responseEntity;
    } catch (Exception ex) {
      ex.printStackTrace();
      Error error = new Error(500, "内部服务器错误：" + ex.getMessage());
      responseEntity = new ResponseEntity<Object>(error, HttpStatus.INTERNAL_SERVER_ERROR);
      return responseEntity;
    }
  }

  /**
   * 结算前准备接口.
   */
  @RequestMapping(value = "prepare", method = RequestMethod.POST)
  public ResponseEntity<Object> prepare(
      @RequestParam("orderId") Long orderId, 
      @RequestParam("appKey") String appKey) {
    ResponseEntity<Object> responseEntity = null;
    appKey = StringUtils.trimToEmpty(appKey);
    Preconditions.checkArgument(StringUtils.isNotBlank(appKey), "AppKey不能为空");
    try {
      Boolean bool = Boolean.FALSE;
      bool = orderManager.prepare(orderId,appKey);
      Result<Boolean> result = new Result<Boolean>(0, "成功", bool);
      responseEntity = new ResponseEntity<Object>(result, HttpStatus.CREATED);

      return responseEntity;
    } catch (Exception ex) {
      ex.printStackTrace();
      Error error = new Error(500, "内部服务器错误：" + ex.getMessage());
      responseEntity = new ResponseEntity<Object>(error, HttpStatus.INTERNAL_SERVER_ERROR);
      return responseEntity;
    }
  }
  
  /**
   * 结算专车订单.
   * @param orderId 订单Id
   * @param afterPayTypeDetail 后支付类型
   * @param companyProfit 公司收入
   * @param employProfit 司机收入
   */
  
  @RequestMapping(value = "finishTask", method = RequestMethod.POST)
  public ResponseEntity<Object> finishTask(
      @RequestParam("orderId") Long orderId, 
      @RequestParam("companyProfit") Double companyProfit,
      @RequestParam("employProfit") Double employProfit, 
      @RequestParam(required = false, value = "afterPayTypeDetail") String afterPayTypeDetail,
      @RequestParam(required = false,value = "signMoney") Double signMoney,
      @RequestParam(required = false,value = "balanceMoney") Double balanceMoney,
      @RequestParam(required = false,value = "alipayMoney") Double alipayMoney, 
      @RequestParam(required = false,value = "weixinMoney") Double weixinMoney,
      @RequestParam(required = false,value = "unionpayMoney") Double unionpayMoney,
      @RequestParam(required = false, value = "cashMoney") Double cashMoney,
      @RequestParam(required = false, value = "operating") String operating,// 后台完工操作人
      @RequestParam(required = false, value = "endAddress") String endAddress,
      @RequestParam(required = false, value = "endLat") Double endLat,
      @RequestParam(required = false,value = "endLng") Double endLng,
      @RequestParam(required = false, value = "runTime") Integer runTime, 
      @RequestParam(required = false, value = "mileage") Double mileage,
      @RequestParam(required = false,value = "midwayWait") Integer midwayWait,
      @RequestParam(required = false,value = "realPay") Double realPay,
      @RequestParam(required = false, value = "guoluMoney") Double guoluMoney,
      @RequestParam(required = false, value = "baoxiaoMoney") Double baoxiaoMoney, 
      @RequestParam(required = false, value = "baoxiaoMemo") String baoxiaoMemo,
      @RequestParam(required = false, value = "employMemo") String employMemo, 
      @RequestParam(required = false, value = "finishTime") Long finishTime,// 后台完工参数
      @RequestParam("appKey") String appKey) {
    ResponseEntity<Object> responseEntity = null;
    appKey = StringUtils.trimToEmpty(appKey);
    Preconditions.checkArgument(StringUtils.isNotBlank(appKey), "AppKey不能为空");
    Order order =
        orderManager.finishTask(orderId, afterPayTypeDetail, companyProfit, employProfit,
            signMoney, balanceMoney, alipayMoney, weixinMoney, unionpayMoney, cashMoney,
            appKey, operating,
            endAddress, endLat, endLng, runTime, mileage, midwayWait, realPay, guoluMoney,
            baoxiaoMoney, baoxiaoMemo, finishTime);
    if (StringUtils.isNotBlank(operating) && StringUtils.isNotBlank(employMemo)) {
      OrderMemo orderMemo = new OrderMemo();
      orderMemo.setMemo(employMemo);
      orderMemo.setOperator(operating);
      orderMemo.setOrderId(order.getId());
      orderMemo.setOrderNo(order.getOrderNo());
      orderMemo.setCreated(new Date());
      orderMemo.setUpdated(new Date());
      orderMemoManager.insert(orderMemo);
    }
    try {
      Result<Order> result = new Result<Order>(0, "成功", order);
      responseEntity = new ResponseEntity<Object>(result, HttpStatus.CREATED);

      return responseEntity;
    } catch (Exception ex) {
      ex.printStackTrace();
      Error error = new Error(500, "内部服务器错误：" + ex.getMessage());
      responseEntity = new ResponseEntity<Object>(error, HttpStatus.INTERNAL_SERVER_ERROR);
      return responseEntity;
    }
  }

  /**
   * 根据服务人员Id查询订单列表.
   * @param employId 服务人员id
   */
  
  @RequestMapping(value = "findByEmployId", method = RequestMethod.GET)
  public ResponseEntity<Object> findByEmployId(
      @RequestParam("employId") Long employId,
      @RequestParam("appKey") String appKey) {
    ResponseEntity<Object> responseEntity = null;
    Preconditions.checkArgument(StringUtils.isNotBlank(appKey), "AppKey不能为空");
    Preconditions.checkArgument(employId != null, "服务人员Id不能为空");
    try {
      OrderQuery orderQuery = new OrderQuery();
      orderQuery.setEmployId(employId);
      orderQuery.setAppKey(appKey);
      orderQuery.setStatusArray("1,2,3,4");
      
      List<Order> orderlist = orderManager.findByEmployId(orderQuery);

      Result<List<Order>> result = new Result<List<Order>>(0, "成功", orderlist);
      responseEntity = new ResponseEntity<Object>(result, HttpStatus.OK);
      return responseEntity;
    } catch (Exception ex) {
      ex.printStackTrace();
      Error error = new Error(500, "内部服务器错误：" + ex.getMessage());
      responseEntity = new ResponseEntity<Object>(error, HttpStatus.INTERNAL_SERVER_ERROR);
      return responseEntity;
    }
  }
  
  /**
   * 统计服务人员未执行中未确认费用订单数量.
   */
  
  @RequestMapping(value = "countByEmployId", method = RequestMethod.GET)
  public ResponseEntity<Object> countByEmployId(
      @RequestParam("employId") Long employId,
      @RequestParam("appKey") String appKey) {
    ResponseEntity<Object> responseEntity = null;
    Preconditions.checkArgument(StringUtils.isNotBlank(appKey), "AppKey不能为空");
    Preconditions.checkArgument(employId != null, "服务人员Id不能为空");
    try {
      OrderQuery orderQuery = new OrderQuery();
      orderQuery.setEmployId(employId);
      orderQuery.setAppKey(appKey);
      orderQuery.setStatusArray("1,2,3,4");
      orderQuery.setTreatment(Boolean.FALSE);
      orderQuery.setBookStatus(0);
      
      Long total = orderManager.countByParam(orderQuery);
      
      Result<Long> result = new Result<Long>(0, "成功", total );
      responseEntity = new ResponseEntity<Object>(result, HttpStatus.OK);
      return responseEntity;
    } catch (Exception ex) {
      ex.printStackTrace();
      Error error = new Error(500, "内部服务器错误：" + ex.getMessage());
      responseEntity = new ResponseEntity<Object>(error, HttpStatus.INTERNAL_SERVER_ERROR);
      return responseEntity;
    }
  }

  /**
   * 催单更新催促时间.
   * @param orderId 订单id
   */
  
  @RequestMapping(value = {"hasten"}, method = RequestMethod.GET)
  public ResponseEntity<Object> hastenOrder(
      @RequestParam("orderId") Long orderId,
      @RequestParam("appKey") String appKey) {
    ResponseEntity<Object> responseEntity = null;
    appKey = StringUtils.trimToEmpty(appKey);
    Preconditions.checkArgument(StringUtils.isNotBlank(appKey), "AppKey不能为空");
    try {

      Order order = orderManager.findByIdAndAppKey(orderId, appKey);
      if (order.getStatus() != 5 && order.getStatus() != 6) {
        order.setLasturge(new Date());
        order.setIsClosed(Boolean.FALSE);
        orderManager.update(order);
      }
      Result<Order> result = new Result<Order>(0, "成功", order);
      responseEntity = new ResponseEntity<Object>(result, HttpStatus.OK);

      return responseEntity;

    } catch (Exception ex) {
      ex.printStackTrace();
      Error error = new Error(500, "内部服务器错误：" + ex.getMessage());
      responseEntity = new ResponseEntity<Object>(error, HttpStatus.INTERNAL_SERVER_ERROR);
      return responseEntity;
    }
  }

  /**
   * 关闭催促提示框.
   */
  
  @RequestMapping(value = {"closeHasten"}, method = RequestMethod.PUT)
  public ResponseEntity<Object> closeHasten(
      @RequestParam("orderId") Long orderId,
      @RequestParam("appKey") String appKey) {
    ResponseEntity<Object> responseEntity = null;
    appKey = StringUtils.trimToEmpty(appKey);
    Preconditions.checkArgument(StringUtils.isNotBlank(appKey), "AppKey不能为空");
    try {

      Order order = orderManager.findByIdAndAppKey(orderId, appKey);
      order.setIsClosed(Boolean.TRUE);
      orderManager.update(order);
      Result<Order> result = new Result<Order>(0, "成功", order);
      responseEntity = new ResponseEntity<Object>(result, HttpStatus.OK);

      return responseEntity;

    } catch (Exception ex) {
      ex.printStackTrace();
      Error error = new Error(500, "内部服务器错误：" + ex.getMessage());
      responseEntity = new ResponseEntity<Object>(error, HttpStatus.INTERNAL_SERVER_ERROR);
      return responseEntity;
    }
  }

  /**
   * 查询十个订单最早催促的订单,按催促时间顺序排序.
   */
  
  @RequestMapping(value = {"getHastenOrder"}, method = RequestMethod.GET)
  public ResponseEntity<Object> getHastenOrder(
      @RequestParam("appKey") String appKey) {
    ResponseEntity<Object> responseEntity = null;
    appKey = StringUtils.trimToEmpty(appKey);
    Preconditions.checkArgument(StringUtils.isNotBlank(appKey), "AppKey不能为空");
    try {
      List<Order> list = orderManager.findHastenOrderAppKey(appKey);

      Result<List<Order>> result = new Result<List<Order>>(0, "成功", list);
      responseEntity = new ResponseEntity<Object>(result, HttpStatus.OK);

      return responseEntity;

    } catch (Exception ex) {
      ex.printStackTrace();
      Error error = new Error(500, "内部服务器错误：" + ex.getMessage());
      responseEntity = new ResponseEntity<Object>(error, HttpStatus.INTERNAL_SERVER_ERROR);
      return responseEntity;
    }
  }

  /**
   * 临时表订单转存到真实表中 预付费后新增订单到真实订单.
   * @param orderId 订单id
   * @param prePayTypeDetail 预支付类型
   */
  
  @RequestMapping(value = "tempToForever", method = RequestMethod.GET)
  public ResponseEntity<Object> tempToForever(
      @RequestParam("orderId") Long orderId,
      @RequestParam("prePayTypeDetail") String prePayTypeDetail,
      @RequestParam("appKey") String appKey) {
    ResponseEntity<Object> responseEntity = null;
    try {
      OrderTemp temp = orderTempManager.findByIdAndAppKey(orderId, appKey);
      Order order = null;
      // 没有处理过的临时订单,把临时订单放到真实订单里
      if (!temp.getTreatment()) { 
        order = orderManager.tempToForever(prePayTypeDetail, temp.getCompanyId(),
                temp.getCompanyName(), temp.getPassengerId(), temp.getPassengerName(),
                temp.getPassengerPhone(), temp.getShowPhone(), temp.getCarTypeId(),
                temp.getChannelName(), temp.getStartAddress(), temp.getStartAddressDetail(),
                temp.getStartLat(), temp.getStartLng(), temp.getEndAddress(),
                temp.getEndAddressDetail(), temp.getEndLat(), temp.getEndLng(),
                temp.getServerTime(), temp.getStartPrice(), temp.getMileagePrice(),
                temp.getRunTimePrice(), temp.getBudgetPay(), temp.getCouponId(), temp.getRealPay(),
                temp.getRunTime(), temp.getMileage(), appKey);
        orderTempManager.update(orderId, appKey);
      }

      Result<Order> result = new Result<Order>(0, "成功", order);

      responseEntity = new ResponseEntity<Object>(result, HttpStatus.CREATED);
      return responseEntity;
    } catch (Exception ex) {
      ex.printStackTrace();
      Error error = new Error(500, "内部服务器错误：" + ex.getMessage());
      responseEntity = new ResponseEntity<Object>(error, HttpStatus.INTERNAL_SERVER_ERROR);
      return responseEntity;
    }
  }

  /**
   * 获取单个临时订单的接口.
   * @param orderId 临时订单id
   */
  
  @RequestMapping(value = "getOrderTemp", method = RequestMethod.GET)
  public ResponseEntity<Object> getOrderTemp(
      @RequestParam("orderId") Long orderId,
      @RequestParam("appKey") String appKey) {
    ResponseEntity<Object> responseEntity = null;
    try {
      OrderTemp order = orderTempManager.findByIdAndAppKey(orderId, appKey);
      Map<String, Object> map = new HashMap<String, Object>();
      map.put("id", order.getId());
      map.put("budgetPay", order.getBudgetPay());
      map.put("treatment", order.getTreatment());
      map.put("couponId", order.getCouponId());
      Result<Map<String, Object>> result = new Result<Map<String, Object>>(0, "成功", map);

      responseEntity = new ResponseEntity<Object>(result, HttpStatus.CREATED);
      return responseEntity;
    } catch (Exception ex) {
      ex.printStackTrace();
      Error error = new Error(500, "内部服务器错误：" + ex.getMessage());
      responseEntity = new ResponseEntity<Object>(error, HttpStatus.INTERNAL_SERVER_ERROR);
      return responseEntity;
    }
  }
  /**
   * 查询统计数据.
   * @param year 年份
   */
  
  @RequestMapping(value = {"zhuancheDataForYear"}, method = RequestMethod.GET)
  public ResponseEntity<Object> zhuancheDataForYear(
      @RequestParam("year") Integer year,
      @RequestParam(required = false) Long companyId, 
      @RequestParam("appKey") String appKey) {
    ResponseEntity<Object> responseEntity = null;
    appKey = StringUtils.trimToEmpty(appKey);

    Preconditions.checkArgument(StringUtils.isNotBlank(appKey), "AppKey不能为空");
    try {
      ChartYear charYear = orderManager.dataForYear(year, companyId, appKey);

      Result<ChartYear> result = new Result<ChartYear>(0, "成功", charYear);
      responseEntity = new ResponseEntity<Object>(result, HttpStatus.OK);
      return responseEntity;

    } catch (Exception ex) {
      ex.printStackTrace();
      Error error = new Error(500, "内部服务器错误：" + ex.getMessage());
      responseEntity = new ResponseEntity<Object>(error, HttpStatus.INTERNAL_SERVER_ERROR);
      return responseEntity;
    }
  }
  /**
   * 统计接口.
   * @param year 年
   * @param companyId 公司id
   * @param month 月
   */
  
  @RequestMapping(value = {"zhuancheDataForMonth"}, method = RequestMethod.GET)
  public ResponseEntity<Object> zhuancheDataForMonth(
      @RequestParam("year") Integer year,
      @RequestParam(required = false) Long companyId,
      @RequestParam(required = false) Integer month, 
      @RequestParam("appKey") String appKey) {
    ResponseEntity<Object> responseEntity = null;
    appKey = StringUtils.trimToEmpty(appKey);

    Preconditions.checkArgument(StringUtils.isNotBlank(appKey), "AppKey不能为空");
    try {
      ChartMonth chartMonth = orderManager.dataForMonth(year, companyId, month, appKey);

      Result<ChartMonth> result = new Result<ChartMonth>(0, "成功", chartMonth);
      responseEntity = new ResponseEntity<Object>(result, HttpStatus.OK);
      return responseEntity;

    } catch (Exception ex) {
      ex.printStackTrace();
      Error error = new Error(500, "内部服务器错误：" + ex.getMessage());
      responseEntity = new ResponseEntity<Object>(error, HttpStatus.INTERNAL_SERVER_ERROR);
      return responseEntity;
    }
  }
  /**
   * 统计数据.
   * @param year 年
   * @param day 日
   * @param companyId 公司id
   * @param month 月
   */
  
  @RequestMapping(value = {"zhuancheDataForDay"}, method = RequestMethod.GET)
  public ResponseEntity<Object> zhuancheDataForDay(
      @RequestParam("year") Integer year,
      @RequestParam("day") Integer day,
      @RequestParam(value = "companyId", required = false) Long companyId, 
      @RequestParam(value = "month", required = false) Integer month, 
      @RequestParam("appKey") String appKey) {
    ResponseEntity<Object> responseEntity = null;
    appKey = StringUtils.trimToEmpty(appKey);

    Preconditions.checkArgument(StringUtils.isNotBlank(appKey), "AppKey不能为空");
    try {
      ChartDay chartDay = orderManager.dataForDay(year, month, day, companyId, appKey);

      Result<ChartDay> result = new Result<ChartDay>(0, "成功", chartDay);
      responseEntity = new ResponseEntity<Object>(result, HttpStatus.OK);
      return responseEntity;

    } catch (Exception ex) {
      ex.printStackTrace();
      Error error = new Error(500, "内部服务器错误：" + ex.getMessage());
      responseEntity = new ResponseEntity<Object>(error, HttpStatus.INTERNAL_SERVER_ERROR);
      return responseEntity;
    }
  }
  /**
   * 统计数据.
   * @param start 开始时间
   * @param end 结束时间
   * @param employId 员工id
   * @param offset 分页参数
   * @param size 分页参数
   */
  
  @RequestMapping(value = {"zhuancheEmployOrder"}, method = RequestMethod.GET)
  public ResponseEntity<Object> zhuancheEmployOrder(
      @RequestParam("start") Date start,
      @RequestParam("end") Date end,
      @RequestParam(value = "employId", required = false) Long employId, 
      @RequestParam(value = "offset", required = false) Integer offset,
      @RequestParam(value = "size",required = false) Integer size,
      @RequestParam("appKey") String appKey) {
    ResponseEntity<Object> responseEntity = null;
    appKey = StringUtils.trimToEmpty(appKey);

    Preconditions.checkArgument(StringUtils.isNotBlank(appKey), "AppKey不能为空");
    try {
      Order order = orderManager.findFinishedByDriverWithDate(employId, start, end, appKey);
      Result<Order> result = new Result<Order>(0, "成功", order);
      responseEntity = new ResponseEntity<Object>(result, HttpStatus.OK);
      return responseEntity;

    } catch (Exception ex) {
      ex.printStackTrace();
      Error error = new Error(500, "内部服务器错误：" + ex.getMessage());
      responseEntity = new ResponseEntity<Object>(error, HttpStatus.INTERNAL_SERVER_ERROR);
      return responseEntity;
    }
  }

  /**
   * 热力图.
   * @param year 年
   * @param month 月
   */
  
  @RequestMapping(value = {"zhuanHeatMap"}, method = RequestMethod.GET)
  public ResponseEntity<Object> zhuanHeatMap(
      @RequestParam("year") Integer year,
      @RequestParam("month") Integer month,
      @RequestParam("appKey") String appKey) {
    ResponseEntity<Object> responseEntity = null;
    appKey = StringUtils.trimToEmpty(appKey);

    Preconditions.checkArgument(StringUtils.isNotBlank(appKey), "AppKey不能为空");
    try {
      List<Order> order = orderManager.findMonthOrder(year, month, appKey);
      Result<List<Order>> result = new Result<List<Order>>(0, "成功", order);
      responseEntity = new ResponseEntity<Object>(result, HttpStatus.OK);
      return responseEntity;

    } catch (Exception ex) {
      ex.printStackTrace();
      Error error = new Error(500, "内部服务器错误：" + ex.getMessage());
      responseEntity = new ResponseEntity<Object>(error, HttpStatus.INTERNAL_SERVER_ERROR);
      return responseEntity;
    }
  }
  /**
   * 统计客户数据.
   * @param companyId 公司id
   * @param startTime 开始时间
   * @param endTime 结束时间
   */
  
  @RequestMapping(value = {"zhuanMemberOrder"}, method = RequestMethod.GET)
  public ResponseEntity<Object> zhuanMemberOrder(
      @RequestParam(value = "companyId", required = false) Long companyId,
      @RequestParam(required = false, value = "startTime") Long startTime, 
      @RequestParam(required = false, value = "endTime") Long endTime,
      @RequestParam("appKey") String appKey) {
    ResponseEntity<Object> responseEntity = null;
    appKey = StringUtils.trimToEmpty(appKey);

    Preconditions.checkArgument(StringUtils.isNotBlank(appKey), "AppKey不能为空");
    try {
      Date startdate = null;
      Date enddate = null;
      if (startTime != null) {
        startdate = new Date(startTime);
      }
      if (endTime != null) {
        enddate = new Date(endTime);
      }

      PageVo<MemberOrderVo> order =
          orderManager.findMemberOrder(startdate, enddate, companyId, appKey);
      Result<PageVo<MemberOrderVo>> result = new Result<PageVo<MemberOrderVo>>(0, "成功", order);
      responseEntity = new ResponseEntity<Object>(result, HttpStatus.OK);
      return responseEntity;

    } catch (Exception ex) {
      ex.printStackTrace();
      Error error = new Error(500, "内部服务器错误：" + ex.getMessage());
      responseEntity = new ResponseEntity<Object>(error, HttpStatus.INTERNAL_SERVER_ERROR);
      return responseEntity;
    }
  }
  /**
   * 查询订单来源.
   * @param startDate 开始时间
   * @param endDate 结束时间
   * @param companyId 公司id
   */
  
  @RequestMapping(value = "orderFromSource", method = RequestMethod.GET)
  public ResponseEntity<Object> orderFromSource(
      @RequestParam(required = false, value = "startDate") Long startDate, 
      @RequestParam(required = false, value = "endDate") Long endDate,
      @RequestParam(value = "companyId",required = false) Long companyId,
      @RequestParam("appKey") String appKey) {
    appKey = StringUtils.trimToEmpty(appKey);
    ResponseEntity<Object> responseEntity = null;
    try {
      Date date1 = null;
      Date date2 = null;
      if (startDate != null) {
        date1 = new Date(startDate);
      }
      if (endDate != null) {
        date2 = new Date(endDate);
      }
      Preconditions.checkArgument(StringUtils.isNotBlank(appKey), "AppKey不能为空");
      PageVo<OrderFromSourceVo> orderFromSources =
          orderManager.orderFromSource(date1, date2, companyId, appKey);

      Result<PageVo<OrderFromSourceVo>> result =
          new Result<PageVo<OrderFromSourceVo>>(0, "成功", orderFromSources);
      responseEntity = new ResponseEntity<Object>(result, HttpStatus.OK);
      return responseEntity;

    } catch (Exception ex) {
      ex.printStackTrace();
      Error error = new Error(500, "内部服务器错误：" + ex.getMessage());
      responseEntity = new ResponseEntity<Object>(error, HttpStatus.INTERNAL_SERVER_ERROR);
      return responseEntity;
    }
  }
  /**
   * 统计数据.
   * @param startDate 开始时间
   * @param endDate 结束时间
   * @param empCompanyId 司机公司id
   */
  
  @RequestMapping(value = "driverAchievement", method = RequestMethod.GET)
  public ResponseEntity<Object> driverAchievement(
      @RequestParam(value = "startDate",required = false) Long startDate,
      @RequestParam(value = "endDate", required = false) Long endDate, 
      @RequestParam(value = "companyId", required = false) Long empCompanyId,
      @RequestParam("appKey") String appKey) {
    appKey = StringUtils.trimToEmpty(appKey);
    ResponseEntity<Object> responseEntity = null;
    try {
      Date date1 = null;
      Date date2 = null;
      if (startDate != null) {
        date1 = new Date(startDate);
      }
      if (endDate != null) {
        date2 = new Date(endDate);
      }
      Preconditions.checkArgument(StringUtils.isNotBlank(appKey), "AppKey不能为空");
      PageVo<DriverOrderVo> orderFromSources =
          orderManager.driverAchievement(date1, date2, empCompanyId, appKey);

      Result<PageVo<DriverOrderVo>> result =
          new Result<PageVo<DriverOrderVo>>(0, "成功", orderFromSources);
      responseEntity = new ResponseEntity<Object>(result, HttpStatus.OK);
      return responseEntity;

    } catch (Exception ex) {
      ex.printStackTrace();
      Error error = new Error(500, "内部服务器错误：" + ex.getMessage());
      responseEntity = new ResponseEntity<Object>(error, HttpStatus.INTERNAL_SERVER_ERROR);
      return responseEntity;
    }


  }
  /**
   * 统计接口.
   * @param startDate 开始时间
   * @param endDate 结束时间
   */
  
  @RequestMapping(value = "companyOrder", method = RequestMethod.GET)
  public ResponseEntity<Object> companyOrder(
      @RequestParam(required = false, value = "startDate") Long startDate, 
      @RequestParam(required = false, value = "endDate") Long endDate,
      @RequestParam("appKey") String appKey) {
    appKey = StringUtils.trimToEmpty(appKey);
    ResponseEntity<Object> responseEntity = null;
    try {
      Date date1 = null;
      Date date2 = null;
      if (startDate != null) {
        date1 = new Date(startDate);
      }
      if (endDate != null) {
        date2 = new Date(endDate);
      }
      Preconditions.checkArgument(StringUtils.isNotBlank(appKey), "AppKey不能为空");
      PageVo<CompanyOrderVo> orderFromSources = orderManager.companyOrder(date1, date2, appKey);

      Result<PageVo<CompanyOrderVo>> result =
          new Result<PageVo<CompanyOrderVo>>(0, "成功", orderFromSources);
      responseEntity = new ResponseEntity<Object>(result, HttpStatus.OK);
      return responseEntity;

    } catch (Exception ex) {
      ex.printStackTrace();
      Error error = new Error(500, "内部服务器错误：" + ex.getMessage());
      responseEntity = new ResponseEntity<Object>(error, HttpStatus.INTERNAL_SERVER_ERROR);
      return responseEntity;
    }
  }
  /**
   * 统计接口.
   * @param driverId 司机id
   * @param startDate 开始时间
   * @param endDate 结束时间
   * @param page 分页参数
   * @param rows 分页参数
   */

  @RequestMapping(value = "driverOrderDetailVo", method = RequestMethod.GET)
  public ResponseEntity<Object> driverOrderDetailVo(
      @RequestParam("driverId") Long driverId,
      @RequestParam(required = false, value = "startDate") Long startDate,
      @RequestParam(required = false, value = "endDate") Long endDate, 
      @RequestParam(required = false, value = "page") Integer page,
      @RequestParam(required = false, value = "rows") Integer rows,
      @RequestParam("appKey") String appKey) {
    appKey = StringUtils.trimToEmpty(appKey);
    ResponseEntity<Object> responseEntity = null;
    try {
      Date date1 = null;
      Date date2 = null;
      if (startDate != null) {
        date1 = new Date(startDate);
      }
      if (endDate != null) {
        date2 = new Date(endDate);
      }
      Preconditions.checkArgument(StringUtils.isNotBlank(appKey), "AppKey不能为空");
      PageVo<DriverOrderDetailVo> driverDetailVo =
          orderManager.driverOrderDetailVo(driverId, date1, date2, page, rows, appKey);

      Result<PageVo<DriverOrderDetailVo>> result =
          new Result<PageVo<DriverOrderDetailVo>>(0, "成功", driverDetailVo);
      responseEntity = new ResponseEntity<Object>(result, HttpStatus.OK);
      return responseEntity;

    } catch (Exception ex) {
      ex.printStackTrace();
      Error error = new Error(500, "内部服务器错误：" + ex.getMessage());
      responseEntity = new ResponseEntity<Object>(error, HttpStatus.INTERNAL_SERVER_ERROR);
      return responseEntity;
    }
  }

  /**
   * 统计订单所有数据.
   * @param companyId 公司Id
   * @param start 开始时间
   * @param end 结束时间
   * @param maincompany 是否是主公司
   * @param appKey 区分系统
   * @return 订单总金额,单量,公司收入,司机收入 主公司加所有完成订单量,所有销单量,所有公司收入,所有司机收入,所有订单金额(realpay)
   */
  
  @RequestMapping(value = {"chart"}, method = RequestMethod.GET)
  public ResponseEntity<Object> countAccount(
      @RequestParam(required = false, value = "companyId") Long companyId,
      @RequestParam(required = false, value = "start") Long start,
      @RequestParam(required = false, value = "end") Long end, 
      @RequestParam("maincompany") Boolean maincompany,
      @RequestParam("appKey") String appKey) {
    ResponseEntity<Object> responseEntity = null;
    appKey = StringUtils.trimToEmpty(appKey);
    Preconditions.checkArgument(StringUtils.isNotBlank(appKey), "AppKey不能为空");
    try {
      Map<String, Object> map = new HashMap<String, Object>();
      map = orderManager.chart(companyId, start, end, maincompany, appKey);
      Result<Map<String, Object>> result = new Result<Map<String, Object>>(0, "成功", map);
      responseEntity = new ResponseEntity<Object>(result, HttpStatus.OK);
      return responseEntity;
    } catch (Exception ex) {
      ex.printStackTrace();
      Error error = new Error(500, "内部服务器错误：" + ex.getMessage());

      responseEntity = new ResponseEntity<Object>(error, HttpStatus.INTERNAL_SERVER_ERROR);

      return responseEntity;
    }

  }

  /**
   * 修改订单金额.
   */
  
  @RequestMapping(value = "updateRealMoney", method = RequestMethod.POST)
  public ResponseEntity<Object> updateRealMoney(
      @RequestParam("orderId") Long orderId,
      @RequestParam("couponMoney") Double couponMoney,
      @RequestParam("cashMoney") Double cashMoney,
      @RequestParam("signMoney") Double signMoney,
      @RequestParam("balanceMoney") Double balanceMoney,
      @RequestParam("alipayMoney") Double alipayMoney,
      @RequestParam("weixinMoney") Double weixinMoney,
      @RequestParam("operator") String operator,
      @RequestParam("content") String content,
      @RequestParam("appKey") String appKey) {
    ResponseEntity<Object> responseEntity = null;
    appKey = StringUtils.trimToEmpty(appKey);
    Preconditions.checkArgument(StringUtils.isNotBlank(appKey), "AppKey不能为空");
    Boolean checkExist = orderManager.checkExist(orderId, appKey);
    Preconditions.checkArgument(checkExist, "订单不存在");
    try {
      orderManager.updateRealMoney(orderId, couponMoney, cashMoney, signMoney, balanceMoney,
          alipayMoney, weixinMoney, operator, content, appKey);

      Result<Order> result = new Result<Order>(0, "成功", null);

      responseEntity = new ResponseEntity<Object>(result, HttpStatus.CREATED);

      return responseEntity;
    } catch (Exception ex) {
      ex.printStackTrace();
      Error error = new Error(-4, "内部服务器错误：" + ex.getMessage());
      responseEntity = new ResponseEntity<Object>(error, HttpStatus.INTERNAL_SERVER_ERROR);
      return responseEntity;
    }
  }

  /**
   * 查询某个服务人员的指定时间段的专车订单完成时间.
   */
  
  @RequestMapping(value = "queryFinishOrderByEmployId", method = RequestMethod.GET)
  public ResponseEntity<Object> queryFinishOrderByEmployId(
      @RequestParam("employId") Long employId,
      @RequestParam(required = false, value = "start") Long start,
      @RequestParam(required = false, value = "end") Long end,
      @RequestParam(required = false, value = "orderby") String orderby, 
      @RequestParam("page") Integer page,
      @RequestParam("rows") Integer rows, 
      @RequestParam("appKey") String appKey) {
    ResponseEntity<Object> responseEntity = null;
    appKey = StringUtils.trimToEmpty(appKey);
    Preconditions.checkArgument(StringUtils.isNotBlank(appKey), "AppKey不能为空");
    try {
      OrderQuery orderQuery = new OrderQuery();
      orderQuery.setAppKey(appKey);
      orderQuery.setEmployId(employId);
      orderQuery.setStatusArray("5");
      orderQuery.setPage(page);
      orderQuery.setRows(rows);
      if (StringUtils.isNotBlank(orderby)) {
        orderQuery.setOrderby(orderby);
      }
      if (start != null) {
        orderQuery.setStartFinishTime(start);
      }
      if (end != null) {
        orderQuery.setEndFinishTime(end);
      }
      DataGrid<Order> dataGrid = new DataGrid<Order>();
      dataGrid = orderManager.queryFinishOrder(orderQuery);
      
      Result<DataGrid<Order>> result = new Result<DataGrid<Order>>(0, "成功", dataGrid);

      responseEntity = new ResponseEntity<Object>(result, HttpStatus.OK);
      return responseEntity;
    } catch (Exception ex) {
      ex.printStackTrace();
      Error error = new Error(-4, "内部服务器错误：" + ex.getMessage());
      responseEntity = new ResponseEntity<Object>(error, HttpStatus.INTERNAL_SERVER_ERROR);
      return responseEntity;
    }
  }
  /**
   * 查询未完成和已完成订单.
   */
  @RequestMapping(value = "queryFinishOrder", method = RequestMethod.GET)
  public ResponseEntity<Object> queryFinishOrder(
      @RequestParam("employId") Long employId,
      @RequestParam(required = false, value = "start") Long start,
      @RequestParam(required = false, value = "end") Long end,
      @RequestParam("page") Integer page,
      @RequestParam("rows") Integer rows, 
      @RequestParam("appKey") String appKey) {
    ResponseEntity<Object> responseEntity = null;
    appKey = StringUtils.trimToEmpty(appKey);
    Preconditions.checkArgument(StringUtils.isNotBlank(appKey), "AppKey不能为空");
    try {
      OrderQuery orderQuery = new OrderQuery();
      orderQuery.setAppKey(appKey);
      orderQuery.setEmployId(employId);
      orderQuery.setPage(page);
      orderQuery.setRows(rows);
      if (start != null) {
        orderQuery.setStartFinishTime(start);
      }
      if (end != null) {
        orderQuery.setEndFinishTime(end);
      }
      orderQuery.setOrderby("treatmentDate desc");
      DataGrid<Order> dataGrid = new DataGrid<Order>();
      dataGrid = orderManager.selectFinishOrder(orderQuery);
      
      Result<DataGrid<Order>> result = new Result<DataGrid<Order>>(0, "成功", dataGrid);

      responseEntity = new ResponseEntity<Object>(result, HttpStatus.OK);
      return responseEntity;
    } catch (Exception ex) {
      ex.printStackTrace();
      Error error = new Error(-4, "内部服务器错误：" + ex.getMessage());
      responseEntity = new ResponseEntity<Object>(error, HttpStatus.INTERNAL_SERVER_ERROR);
      return responseEntity;
    }
  }

  /**
   * 查询单个乘客的未支付已确认的订单数量(后台的电话下单来源除外).
   * @param passengerId 客户id
   * @return 数量
   */
  
  @RequestMapping(value = {"countByPassengerId"}, method = RequestMethod.GET)
  public ResponseEntity<Object> countByPassengerId(
      @RequestParam("passengerId") Long passengerId,
      @RequestParam("appKey") String appKey) {
    ResponseEntity<Object> responseEntity = null;
    appKey = StringUtils.trimToEmpty(appKey);
    Preconditions.checkArgument(StringUtils.isNotBlank(appKey), "AppKey不能为空");
    try {
      OrderQuery orderQuery = new OrderQuery();
      orderQuery.setAppKey(appKey);
      orderQuery.setPassengerId(passengerId);
      orderQuery.setChannelNameArray("APP预约,微信预约,网站预约");
      orderQuery.setStatusArray("4");
      orderQuery.setTreatment(Boolean.TRUE);
      
      Long number = orderManager.countByParam(orderQuery);
      
      Result<Long> result = new Result<Long>(0, "成功", number);
      
      responseEntity = new ResponseEntity<Object>(result, HttpStatus.OK);
      
      return responseEntity;
    } catch (Exception ex) {
      ex.printStackTrace();
      Error error = new Error(500, "内部服务器错误：" + ex.getMessage());
      responseEntity = new ResponseEntity<Object>(error, HttpStatus.INTERNAL_SERVER_ERROR);
      return responseEntity;
    }
  }

  /**
   * 查询客户当天下单数量包括新单,派单,销单,执行中(后台的电话下单来源除外).
   * @param passengerId 乘客id
   * @param status nocancel
   */
  
  @RequestMapping(value = {"countRunning"}, method = RequestMethod.GET)
  public ResponseEntity<Object> countRunning(
      @RequestParam("passengerId") Long passengerId,
      @RequestParam(required=false,value="status") String status,
      @RequestParam("appKey") String appKey) {
    ResponseEntity<Object> responseEntity = null;
    appKey = StringUtils.trimToEmpty(appKey);
    Preconditions.checkArgument(StringUtils.isNotBlank(appKey), "AppKey不能为空");
    try {
      OrderQuery orderQuery = new OrderQuery();
      orderQuery.setPassengerId(passengerId);
      orderQuery.setAppKey(appKey);
      if (StringUtils.isNotBlank(status) && "nocancel".equals(status)) {
        orderQuery.setChannelNameArray("APP预约,微信预约,网站预约,司机补单,电话预约,APP預約,微信預約,网站預約,司機補單,電話預約");
        orderQuery.setStatusArray("0,1,2,3,4");
      } else {
        orderQuery.setChannelNameArray("APP预约,微信预约,网站预约,APP預約,微信預約,网站預約");
        orderQuery.setStatusArray("0,1,2,3,4,6");
        Calendar calendar = Calendar.getInstance();
        
        calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH));
        calendar.set(Calendar.DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH));
        calendar.set(Calendar.HOUR, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        Date startDate = calendar.getTime();
        orderQuery.setStartTime(startDate.getTime());
        
        calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH));
        calendar.set(Calendar.DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH));
        calendar.set(Calendar.HOUR, 23);
        calendar.add(Calendar.MINUTE, 59);
        calendar.add(Calendar.SECOND, 59);
        Date endDate = calendar.getTime();
        
        orderQuery.setEndTime(endDate.getTime());
      }
      
      
      Long number = orderManager.countByParam(orderQuery);

      Result<Long> result = new Result<Long>(0, "成功", number);

      responseEntity = new ResponseEntity<Object>(result, HttpStatus.OK);

      return responseEntity;
    } catch (Exception ex) {
      ex.printStackTrace();
      Error error = new Error(500, "内部服务器错误：" + ex.getMessage());
      responseEntity = new ResponseEntity<Object>(error, HttpStatus.INTERNAL_SERVER_ERROR);
      return responseEntity;
    }
  }

  /**
   * 查询订单数量.
   * @param employId 服务人员id
   * @param startDate 完成订单时间起点
   * @param endDate 完成订单时间终点
   */
  @RequestMapping(value = "driverOrderDetailCount", method = RequestMethod.GET)
  public ResponseEntity<Object> driverOrderDetailCount(
          @RequestParam("driverId") Long employId,
          @RequestParam(required = false,value = "startDate") Long startDate,
          @RequestParam(required = false,value = "endDate") Long endDate,
          @RequestParam("appKey") String appKey) {
    ResponseEntity<Object> responseEntity = null;
    Preconditions.checkArgument(StringUtils.isNotBlank(appKey), "AppKey不能为空");
    Preconditions.checkArgument(employId != null, "服务人员id不能为空");
    try {

      OrderQuery orderQuery = new OrderQuery();
      orderQuery.setEmployId(employId);
      orderQuery.setStartFinishTime(startDate);
      orderQuery.setEndFinishTime(endDate);
      orderQuery.setAppKey(appKey);
      Long num = orderManager.driverOrderDetailCount(orderQuery);
      Result<Long> result = new Result<Long>(0, "成功", num);
      responseEntity = new ResponseEntity<Object>(result, HttpStatus.OK);
      return responseEntity;
    } catch (Exception ex) {
      ex.printStackTrace();
      Error error = new Error(500, "内部服务器错误：" + ex.getMessage());
      responseEntity = new ResponseEntity<Object>(error, HttpStatus.INTERNAL_SERVER_ERROR);
      return responseEntity;
    }
  }
  
  @RequestMapping("countOnDutyByDriver")
	@ResponseBody
	public ResultTransport countOnDutyByDriver(@RequestParam("driverId") Long driverId, @RequestParam("startTime") Long startTime,
			@RequestParam("endTime") Long endTime) {
		ResultTransport response = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
		try {
			Date start = new Date(startTime);
			Date end = new Date(endTime);
			Map<String, Object> map = orderManager.countOnDutyByDriver(driverId, start, end);
			response.setData(map);
		} catch (Exception e) {
			e.printStackTrace();
			response = ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
		}
		return response;
	}
  
  @RequestMapping("countBookDriver")
	@ResponseBody
	public ResultTransport countBookDriver(@RequestParam(value="zhuanYuyueMax",required=false) Long zhuanYuyueMax, 
			@RequestParam(value="zhuanYuyueTime",required=false) Long zhuanYuyueTime,
			@RequestParam("appKey") String appkey) {
		ResultTransport response = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
		try { 
			Date end = null;
			if (zhuanYuyueTime!=null) {
				end = new Date(zhuanYuyueTime);
			}
			List<Map<String, Object>> list = orderManager.countBookDriver(zhuanYuyueMax, end, appkey);
			response.setData(list);
		} catch (Exception e) {
			e.printStackTrace();
			response = ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
		}
		return response;
	} 
  
  @RequestMapping("countBusyBookDriver")
  @ResponseBody
  public ResultTransport countBusyBookDriver(@RequestParam(value="zhuanYuyueTime",required=true) Long zhuanYuyueTime,
		  @RequestParam("appKey") String appkey) {
	  ResultTransport response = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
	  try { 
		  Date end = null;
		  if (zhuanYuyueTime!=null) {
			  end = new Date(zhuanYuyueTime);
		  }
		  List<Map<String, Object>> list = orderManager.countBusyBookDriver(end, appkey);
		  response.setData(list);
	  } catch (Exception e) {
		  e.printStackTrace();
		  response = ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
	  }
	  return response;
  } 
  
  @RequestMapping("findDriverBusy")
  @ResponseBody
	public ResultTransport findDriverBusy(@RequestParam(value="zhuanYuyueMax",required=false) Long zhuanYuyueMax, 
			@RequestParam(value="zhuanYuyueTime",required=false) Long zhuanYuyueTime,
			@RequestParam(value="employId",required=true)Long employId,
			@RequestParam(value="orderId",required=true)Long orderId,
			@RequestParam("appKey") String appkey) {
		ResultTransport response = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
		try { 
			Date end = null;
			Map<String, Object> map = orderManager.findOneV4up(orderId, appkey);
			String serviceType = map.get("serviceType").toString(); 
	        if ("rizu".equals(serviceType)||"banrizu".equals(serviceType)) {
				String serverTime = map.get("serverTime").toString(); 
				Date temp = new Date(Long.parseLong(serverTime)); 
				SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
				Date start = df.parse(df.format(temp));
				Calendar c = Calendar.getInstance();
		        c.setTime(start);
		        c.add(Calendar.DAY_OF_MONTH, 1);
		        Date endDate = c.getTime();
		        Integer count = orderManager.getTodayBooks(employId, start, endDate);
		        if (count > 0) {
		        	response.setCode(1);
		        	 return response;
				}
		       
			}
		
			if (zhuanYuyueTime!=null) {
				end = new Date(zhuanYuyueTime*1000);
			}
			List<Map<String, Object>> list = orderManager.findDriverBusy(zhuanYuyueMax, end, appkey, employId);
			if (list.size()>0) { 
				response.setCode(1);
			}else{ 
				response.setCode(0);
			}
			if (null==map.get("bookStatus")||0==Integer.parseInt(map.get("bookStatus").toString())) {
				if (zhuanYuyueTime==null) { 
					response.setCode(0);
				}
			} 
		} catch (Exception e) {
			e.printStackTrace();
			response = ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
		}
		return response;
	} 
}
